package com.wangyg.flourfactory.controller;

import com.wangyg.flourfactory.configuration.ApplicationContextHolder;
import com.wangyg.flourfactory.utils.JsonUtil;
import org.springframework.beans.BeansException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangyg6 on 2019/5/22 10:36.
 */
@RestController
public class BeanController {

	@GetMapping("/beans")
	public String[] getBeans() {
		return ApplicationContextHolder.getBeans();
	}

	@GetMapping(value = "bean/{beanName}")
	public Object getBean(@PathVariable String beanName) {
		Object bean = null;
		try {
			bean = ApplicationContextHolder.getBean(beanName);
		} catch (BeansException e) {
			return e.getMessage();
		}
		Field[] declaredFields = bean.getClass().getDeclaredFields();
		Map map = new HashMap();
		for (Field declaredField : declaredFields) {
			declaredField.setAccessible(true);
			String s;
			Object o = null;
			try {
				o = declaredField.get(bean);
			} catch (IllegalAccessException e) {
				continue;
			}
			try {
				s = JsonUtil.serialize(o);
			} catch (Exception e) {
				continue;
			}
			map.put(declaredField.getName(), o);
		}
		return map;
	}
}
